<template>
  <view class="time-pricing-editor">
    <!-- 已设置的分时段价格 -->
    <view v-if="pricingList.length > 0" class="pricing-list">
      <view 
        v-for="(pricing, index) in pricingList" 
        :key="index"
        class="pricing-item"
      >
        <view class="pricing-info">
          <text class="time-range">{{ pricing.start_time }} - {{ pricing.end_time }}</text>
          <text class="price">¥{{ pricing.price }}/时</text>
        </view>
        <view v-if="!disabled" class="pricing-actions">
          <uni-icons type="compose" size="16" color="#007AFF" @click="editPricing(index)"></uni-icons>
          <uni-icons type="trash" size="16" color="#FF3B30" @click="removePricing(index)"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 添加分时段价格 -->
    <view v-if="!disabled" class="add-pricing">
      <button class="add-btn" @click="showAddModal">
        <uni-icons type="plus" size="16" color="#007AFF"></uni-icons>
        <text class="add-text">添加分时段价格</text>
      </button>
    </view>

    <!-- 空状态 -->
    <view v-if="pricingList.length === 0 && disabled" class="empty-state">
      <text class="empty-text">未设置分时段价格</text>
    </view>

    <!-- 添加/编辑弹窗 -->
    <uni-popup ref="pricingPopup" type="center">
      <view class="pricing-modal">
        <view class="modal-header">
          <text class="modal-title">{{ editIndex >= 0 ? '编辑' : '添加' }}分时段价格</text>
          <uni-icons type="close" size="20" @click="closePricingModal"></uni-icons>
        </view>
        <view class="modal-content">
          <uni-forms ref="pricingFormRef" :modelValue="currentPricing" :rules="pricingRules">
            <uni-forms-item label="开始时间" name="start_time" required>
              <uni-datetime-picker 
                v-model="currentPricing.start_time"
                type="time"
                @change="validateTimeRange"
              >
                <template v-slot:default>
                  <uni-easyinput 
                    :value="currentPricing.start_time" 
                    placeholder="选择开始时间"
                    readonly
                  />
                </template>
              </uni-datetime-picker>
            </uni-forms-item>
            <uni-forms-item label="结束时间" name="end_time" required>
              <uni-datetime-picker 
                v-model="currentPricing.end_time"
                type="time"
                @change="validateTimeRange"
              >
                <template v-slot:default>
                  <uni-easyinput 
                    :value="currentPricing.end_time" 
                    placeholder="选择结束时间"
                    readonly
                  />
                </template>
              </uni-datetime-picker>
            </uni-forms-item>
            <uni-forms-item label="价格" name="price" required>
              <view class="input-with-unit">
                <uni-easyinput 
                  v-model="currentPricing.price" 
                  type="digit"
                  placeholder="请输入价格"
                />
                <text class="unit">元/时</text>
              </view>
            </uni-forms-item>
          </uni-forms>
        </view>
        <view class="modal-footer">
          <button class="cancel-btn" @click="closePricingModal">取消</button>
          <button class="confirm-btn" @click="savePricing">确定</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue';
import type { TimeBasedPricing } from '@/types/store';

interface Props {
  modelValue?: string;
  disabled?: boolean;
}

interface Emits {
  (e: 'update:modelValue', value: string): void;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: '',
  disabled: false,
});

const emit = defineEmits<Emits>();

const pricingList = ref<TimeBasedPricing[]>([]);
const pricingPopup = ref<any>(null);
const pricingFormRef = ref<any>(null);
const editIndex = ref(-1);

const currentPricing = reactive<TimeBasedPricing>({
  start_time: '',
  end_time: '',
  price: 0,
});

const pricingRules = {
  start_time: { rules: [{ required: true, errorMessage: '请选择开始时间' }] },
  end_time: { rules: [{ required: true, errorMessage: '请选择结束时间' }] },
  price: { rules: [{ required: true, errorMessage: '请输入价格' }] },
};

const showAddModal = () => {
  editIndex.value = -1;
  resetCurrentPricing();
  pricingPopup.value?.open();
};

const editPricing = (index: number) => {
  editIndex.value = index;
  const pricing = pricingList.value[index];
  Object.assign(currentPricing, pricing);
  pricingPopup.value?.open();
};

const removePricing = (index: number) => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这个分时段价格吗？',
    success: (res) => {
      if (res.confirm) {
        pricingList.value.splice(index, 1);
        updateValue();
      }
    }
  });
};

const resetCurrentPricing = () => {
  currentPricing.start_time = '';
  currentPricing.end_time = '';
  currentPricing.price = 0;
};

const validateTimeRange = () => {
  if (currentPricing.start_time && currentPricing.end_time) {
    if (currentPricing.start_time >= currentPricing.end_time) {
      uni.showToast({ title: '结束时间必须大于开始时间', icon: 'none' });
      return false;
    }
  }
  return true;
};

const checkTimeConflict = (newPricing: TimeBasedPricing, excludeIndex = -1) => {
  for (let i = 0; i < pricingList.value.length; i++) {
    if (i === excludeIndex) continue;
    
    const existing = pricingList.value[i];
    // 检查时间段是否重叠
    if (
      (newPricing.start_time >= existing.start_time && newPricing.start_time < existing.end_time) ||
      (newPricing.end_time > existing.start_time && newPricing.end_time <= existing.end_time) ||
      (newPricing.start_time <= existing.start_time && newPricing.end_time >= existing.end_time)
    ) {
      return true;
    }
  }
  return false;
};

const savePricing = () => {
  pricingFormRef.value.validate().then(() => {
    if (!validateTimeRange()) return;
    
    if (checkTimeConflict(currentPricing, editIndex.value)) {
      uni.showToast({ title: '时间段与已有设置冲突', icon: 'none' });
      return;
    }
    
    const newPricing = { ...currentPricing };
    
    if (editIndex.value >= 0) {
      // 编辑
      pricingList.value[editIndex.value] = newPricing;
    } else {
      // 添加
      pricingList.value.push(newPricing);
    }
    
    // 按开始时间排序
    pricingList.value.sort((a, b) => a.start_time.localeCompare(b.start_time));
    
    updateValue();
    closePricingModal();
  }).catch((err: any) => {
    console.log('表单校验失败', err);
  });
};

const closePricingModal = () => {
  pricingPopup.value?.close();
  resetCurrentPricing();
};

const updateValue = () => {
  const value = pricingList.value.length > 0 ? JSON.stringify(pricingList.value) : '';
  emit('update:modelValue', value);
};

const parseValue = (value: string) => {
  if (!value) {
    pricingList.value = [];
    return;
  }
  
  try {
    const parsed = JSON.parse(value);
    if (Array.isArray(parsed)) {
      pricingList.value = parsed;
    }
  } catch (error) {
    console.error('解析分时段价格数据失败:', error);
    pricingList.value = [];
  }
};

watch(() => props.modelValue, (newVal) => {
  parseValue(newVal || '');
}, { immediate: true });
</script>

<style lang="scss" scoped>
.time-pricing-editor {
  .pricing-list {
    margin-bottom: 16px;
  }

  .pricing-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px;
    background-color: #f8f9fa;
    border-radius: 8px;
    margin-bottom: 8px;
  }

  .pricing-info {
    flex: 1;
  }

  .time-range {
    display: block;
    font-size: 14px;
    color: var(--text-color);
    margin-bottom: 4px;
  }

  .price {
    font-size: 16px;
    font-weight: bold;
    color: var(--primary-color);
  }

  .pricing-actions {
    display: flex;
    gap: 12px;
  }

  .add-pricing {
    margin-bottom: 16px;
  }

  .add-btn {
    width: 100%;
    padding: 12px;
    background-color: #f0f8ff;
    border: 1px dashed var(--primary-color);
    border-radius: 8px;
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 8px;
  }

  .add-text {
    font-size: 14px;
    color: var(--primary-color);
  }

  .empty-state {
    padding: 20px;
    text-align: center;
  }

  .empty-text {
    color: var(--text-color-secondary);
    font-size: 14px;
  }

  .pricing-modal {
    background-color: #fff;
    border-radius: var(--border-radius);
    padding: 20px;
    width: 320px;
    max-width: 90vw;
  }

  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }

  .modal-title {
    font-size: 18px;
    font-weight: bold;
  }

  .modal-content {
    margin-bottom: 20px;
  }

  .input-with-unit {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .unit {
    font-size: 14px;
    color: var(--text-color-secondary);
    white-space: nowrap;
  }

  .modal-footer {
    display: flex;
    gap: 10px;
  }

  .cancel-btn, .confirm-btn {
    flex: 1;
    height: 44px;
    border-radius: var(--border-radius);
    font-size: 16px;
  }

  .cancel-btn {
    background-color: #f5f5f5;
    color: #666;
  }

  .confirm-btn {
    background-color: var(--primary-color);
    color: #fff;
  }
}
</style>